/**
 * MIT License
 *
 * Copyright (C) 2024 Huawei Device Co., Ltd.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
import {
  decompressAndReadJson,
  readLottieJson,
  downLoadImg,
  handleAssets,
  creatJsonDir,
  creatZipDir
} from "../utils/jsonImage";
import request from "@ohos.request";
import fs from '@ohos.file.fs';

const downLoadSouce = (function(){
  const downloadZipMap = new Map();
  const downloadJsonMap = new Map();

  function downLoadJsonSource(jsonUri, callJsonBack, errCallBack) {
    let resultDir = creatJsonDir(jsonUri);
    let flag = downloadJsonMap.has(jsonUri);
    if (flag) {
      let task = setInterval(() => {
        let repeatJsonData = readLottieJson(jsonUri, resultDir.route);
        if (!repeatJsonData) {
          return;
        }
        callJsonBack(repeatJsonData);
        //取消循环检测
        clearInterval(task);
      }, 100);
    } else {
      // 将URI添加到Map中，表示下载已经开始
      downloadJsonMap.set(jsonUri, true);
      let downloadConfig = {
        action: request.agent.Action.DOWNLOAD,
        url: jsonUri,
        overwrite: true,
        method: 'GET',
        saveas: `./${resultDir.jsonName}`,
        mode: request.agent.Mode.FOREGROUND,
        gauge: true,
      };
      request.agent.create(getContext(), downloadConfig).then((task) => {
        task.on('completed', completecallBack);
        task.on('failed', (err) => {
          errCallBack('error', 'download failed!');
          let lottieData = readLottieJson(jsonUri, resultDir.route);
          downloadJsonMap.delete(jsonUri);
          callJsonBack(lottieData);
        })
        task.start((err) => {
          if (err) {
            downloadJsonMap.delete(jsonUri);
            errCallBack('error', err);
          }
        });
      }).catch((err) => {
        downloadJsonMap.delete(jsonUri);
        errCallBack('error', err);
      });
      let completecallBack = (receivedSize, totalSize) => {
        let srcPath = `${getContext().cacheDir}/${resultDir.jsonName}`;
        let destPath = `${resultDir.route}/${resultDir.jsonName}`;
        try {
          // 移动文件
          fs.moveFileSync(srcPath, destPath);
        } catch (err) {
          console.error('moveFile err:' + JSON.stringify(err));
        }
        downloadJsonMap.delete(jsonUri);
        let lottieData = readLottieJson(jsonUri, resultDir.route);
        // 判断assets是否有图片 且 图片的p地址是否是以http或者https开头的

        let isExitNetworkAssets;
        if (lottieData) {
          isExitNetworkAssets = lottieData.assets.some((item) => {
            return item.p && item.p.startsWith('http');
          })
        }
        if (lottieData && lottieData.assets && lottieData.assets.length != 0 && isExitNetworkAssets) {
          downLoadImg(lottieData).then((results) => {
            // 下载成功加载
            let newJsonData = handleAssets(lottieData);
            callJsonBack(newJsonData);
          })
            .catch((err) => {
              // 下载失败时加载缓存
              console.error('Download error:' + JSON.stringify(err));
              errCallBack('error', err);
              let filesJsonData = handleAssets(lottieData);
              callJsonBack(filesJsonData);
            });
        } else {
          // 读取成功从Map中移除条目
          downloadJsonMap.delete(jsonUri);
          callJsonBack(lottieData);
        }
      };
    }
  };

  function downLoadZipSource(zipUri, callZipBack, errCallBack) {
    let routerDir = creatZipDir(zipUri);
    let flag = downloadZipMap.has(zipUri);
    // 检查URI是否已经在下载Map中
    if (flag) {
      let task = setInterval(() => {
        let repeatZipData = readLottieJson(zipUri, routerDir.route);
        if (!repeatZipData) {
          return;
        }
        const parts = routerDir.route.split('/');
        const lastPart = parts.slice(-3);
        const lastPartStr = lastPart.join('/');
        // 修改u路径
        repeatZipData.assets.forEach((item, index) => {
          if (item.id && item.u) {
            item.u = `${lastPartStr}/images/`;
          }
        });
        callZipBack(repeatZipData);
        //取消循环检测
        clearInterval(task);
      }, 100);
    } else {
      // 将URI添加到Map中，表示下载已经开始
      downloadZipMap.set(zipUri, true);
      let downloadConfig = {
        action: request.agent.Action.DOWNLOAD,
        url: zipUri,
        overwrite: true,
        method: 'GET',
        saveas: `./${routerDir.zipName}`,
        mode: request.agent.Mode.FOREGROUND,
        gauge: true,
      };
      request.agent.create(getContext(), downloadConfig).then((task) => {
        task.on('completed', completecallBack);
        task.on('failed', (err) => {
          if (errCallBack) {
            downloadZipMap.delete(zipUri);
            errCallBack('error', 'download failed!');
          }
        })
        task.start((err) => {
          if (err) {
            downloadZipMap.delete(zipUri);
            errCallBack('error', err);
          }
        });
      }).catch((err) => {
        downloadZipMap.delete(zipUri);
        errCallBack('error', err);
      });
      let completecallBack = (receivedSize, totalSize) => {
        decompressAndReadJson(zipUri, `${getContext().cacheDir}`, routerDir.route).then((result) => {
          // 解压成功，从Map中移除条目
          downloadZipMap.delete(zipUri);
          callZipBack(result);
        }).catch((errData) => {
          // 解压失败，从Map中移除条目
          downloadZipMap.delete(zipUri);
          errCallBack('error', errData);
        });
      };
    }
  };

  return {
    downLoadJsonSource: (jsonUri, callJsonBack, errCallBack) => {
      downLoadJsonSource(jsonUri, callJsonBack, errCallBack);
    },
    downLoadZipSource: (zipUri, callZipBack, errCallBack) => {
      downLoadZipSource(zipUri, callZipBack, errCallBack);
    }
  };
}());

export default downLoadSouce;
